<template>
  <div>
    <div class="inline-container">
      <!-- 新增角色 -->
      <el-button type="primary" icon="el-icon-plus" @click="addRole"
        >新增
      </el-button>
      <!-- 搜索框 -->
      <div class="centered-search">
        <el-form :inline="true" :model="sysRoleQuery" class="demo-form-inline">
          <el-form-item label="角色名称">
            <el-input
              v-model="sysRoleQuery.name"
              placeholder="角色名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getRoleData()">查询</el-button>
            <el-button @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 2、分隔线区域 -->
    <el-divider></el-divider>

    <!-- 3、表单 -->
    <el-table :data="roleData" style="width: 100%" border>
      <el-table-column type="index" width="150" label="序号"></el-table-column>
      <el-table-column prop="name" label="角色名称" width="250">
      </el-table-column>
      <el-table-column prop="code" label="code" width="250"> </el-table-column>
      <el-table-column prop="disable" label="角色状态" width="250">
        <template slot-scope="scope">
          <el-switch
            @change="disableChange(scope.row)"
            v-model="scope.row.disable"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="250">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="updRoleInfo(scope.row)"
            title="修改"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteRole(scope.row.id)"
            title="删除"
            v-if="!scope.row.childrens"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="角色名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="code" prop="code" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="form.desc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="disable" :label-width="formLabelWidth">
          <el-switch
            v-model="form.disable"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          label="菜单权限"
          prop="menuIds"
          :label-width="formLabelWidth"
        >
          <el-tree
            :data="menuData"
            :props="defaultProps"
            node-key="id"
            ref="tree"
            show-checkbox
            :default-checked-keys="checkedkeys"
            default-expand-all
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="addOrUpd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, findById, upd, del, updDisable } from "@/services/role";
import { getUserMenuList } from "@/services/menu";
export default {
  name: "role",

  data() {
    return {
      roleData: [],
      total: 0,
      current: 1,
      size: 10,
      sysRoleQuery: {
        name: "",
        current: 1,
        size: 10,
      },
      formLabelWidth: "120px",
      dialogVisible: false,
      dialogTitle: "",
      form: {
        name: "",
        code: "",
        desc: "",
        disable: 0,
        handleType: "ADD",
        menuIds: [],
      },
      defaultProps: {
        children: "childrens",
        label: "name",
      },
      checkedkeys: [],
      menuData: [],
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入code", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        disable: [{ required: true, message: "请选角色状态", trigger: "blur" }],
        menuIds: [
          {
            required: false,
            message: "请至少选择一个菜单",
            trigger: "blur",
          },
        ],
      },
    };
  },

  mounted() {
    this.getRoleData();
  },

  methods: {
    //获取勾选的菜单id
    getCheckedMenuId() {
      const menuIds = [];
      const tree = this.$refs.tree;
      const selectedNodes = tree.getCheckedNodes();
      if (selectedNodes.length !== 0) {
        selectedNodes.forEach((item) => {
          const nodes = tree.getNode(item.id);
          menuIds.push(item.id);
          // 获取顶级父节点
          if (nodes.level > 1) {
            const id = nodes.parent.data.id;
            if (menuIds.indexOf(id) === -1) {
              menuIds.push(id);
            }
          }
        });
      }
      return menuIds;
    },
    //获取菜单列表
    async getUserMenuList() {
      getUserMenuList()
        .then((res) => {
          this.menuData = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    // 新增弹框
    async addRole() {
      await this.getUserMenuList();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]); // 设置默认选中的节点
      });
      this.clearFrom();
      this.dialogVisible = true;
      this.dialogTitle = "新增角色";
    },
    // 修改弹框
    async updRoleInfo(role) {
      this.dialogVisible = true;
      this.checkedkeys = [];
      this.form.id = role.id;
      this.form.code = role.code;
      this.form.desc = role.desc;
      this.form.name = role.name;
      this.form.disable = role.disable;
      this.dialogTitle = "角色编辑";
      this.form.handleType = "UPD";

      await findById(role.id)
        .then((res) => {
          const menuVos = res.data.menuVos;
          if (menuVos.length !== 0) {
            menuVos.forEach((item) => {
              if (item.childrens) {
                item.childrens.forEach((c) => {
                  this.checkedkeys.push(c.id);
                });
              } else {
                this.checkedkeys.push(item.id);
              }
            });
          }
        })
        .catch((error) => {});

      await this.getUserMenuList();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.checkedkeys); // 设置默认选中的节点
      });
    },
    //删除角色
    deleteRole(id) {
      del(id)
        .then((res) => {
          if (res.data) {
            this.getRoleData();
            this.$message({
              type: "success",
              message: "删除成功",
            });
          }
        })
        .catch((error) => {});
    },
    //获取角色列表
    getRoleData() {
      list(this.sysRoleQuery)
        .then((res) => {
          this.total = res.data.total;
          this.current = res.data.current;
          this.size - res.data.size;
          this.roleData = res.data.records;
        })
        .catch((error) => {});
    },
    // 重置
    resetForm() {
      this.sysRoleQuery = {
        name: "",
        current: 1,
        size: 10,
      };
      this.getRoleData();
    },
    //分页处理
    handleSizeChange(val) {
      this.sysRoleQuery.size = val;
      this.getRoleData();
    },
    handleCurrentChange(val) {
      this.sysRoleQuery.current = val;
      this.getRoleData();
    },
    close() {
      this.dialogVisible = false;
      this.clearFrom();
    },
    //新增或者修改
    addOrUpd() {
      this.form.menuIds = this.getCheckedMenuId();
      this.$refs.form.validate((valid) => {
        if (valid) {
          //新增
          if (this.form.handleType === "ADD") {
            add(this.form)
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.dialogVisible = false;
                this.getRoleData();
              })
              .catch((error) => {});
          } else {
            //修改
            upd(this.form)
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getRoleData();
              })
              .catch((error) => {});
          }
        } else {
          return false;
        }
      });
    },
    disableChange(roleInfo) {
      updDisable(roleInfo.id, roleInfo.disable)
        .then((res) => {
          if (res.data) {
            this.getRoleData();
            this.$message({
              type: "success",
              message: "修改成功",
            });
          }
        })
        .catch((error) => {});
    },
    clearFrom() {
      this.form = {
        name: "",
        code: "",
        desc: "",
        disable: 0,
        handleType: "ADD",
        menuIds: [],
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.inline-container {
  height: 40px;
  display: flex;
  align-items: center; /* Optional: Align items vertically center if needed */
  .centered-search {
    margin-left: 30%;
    justify-content: center;
    margin-top: 26px;
  }
}
.page {
  display: flex;
  justify-content: flex-end;
}
</style>